﻿#region MIT
/*
Engine Of Evermore (http://code.google.com/p/engineofevermore/)
Copyright (c) 2008, 2009 Michael Woerister

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#endregion

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using EngineOfEvermore.Scene;
using EngineOfEvermore.Editor.Common.Command;
using EngineOfEvermore.Editor.Common;
using System.Diagnostics;
using EngineOfEvermore.Common;
using Blue.ResourceManager;

namespace EngineOfEvermore.Editor.SceneEditor
{
    public class SceneModel : IDisposable
    {
        readonly SceneGraph _sceneGraph;
        FrameUpdater _sceneGraphUpdater = new FrameUpdater();
        readonly CommandStack _commandStack = new CommandStack();
        readonly SceneSelection _sceneSelection;
        String _associatedResourceName;
        int _lastSavedVersion = int.MinValue;
        bool _disposed;
        
        public event Action<SceneModel> NameOfAssociatedResourceChanged;
        public event Action<SceneModel> HasUnsavedChangesChanged;

        private SceneModel( SceneGraph sceneGraph )
        {
            Debug.Assert( sceneGraph != null );

            _sceneSelection = new SceneSelection();
            _sceneGraph = sceneGraph;
            _sceneGraph.OnInit( new System.ComponentModel.Design.ServiceContainer() );

            AgateLib.Core.KeepAliveEvent += _updateSceneGraphUpdater;
            
            _sceneGraphUpdater.TargetFps = 60;

            _commandStack.VersionChanged += _commandStackVersionChanged;
        }

        void _updateSceneGraphUpdater()
        {
            _sceneGraphUpdater.Update( _sceneGraph.Update );
        }

        ~SceneModel()
        {
            this.Dispose( false );
        }

        void _commandStackVersionChanged( CommandStack commandStack )
        {
            if ( this.HasUnsavedChangesChanged != null )
            {
                this.HasUnsavedChangesChanged( this );
            }
        }

        public static SceneModel CreateNewSceneModel()
        {
            return new SceneModel( new SceneGraph() );
        }

        public static SceneModel CreateSceneModelFromResource( String resourceName )
        {
            Debug.Assert( resourceName != null && ResourceManager.ResourceExists( resourceName ) );
            
            SceneModel model = new SceneModel( new SceneGraph() );
            
            var content = ResourceManager
                .GetResource<EngineOfEvermore.Scene.ObjectLibrary.SceneGraphContentResource>( resourceName );
            
            content.AddContentToSceneGraph( model.SceneGraph );
            
            model._associatedResourceName = resourceName;
            model._lastSavedVersion = model._commandStack.Version;

            return model;
        }

        public void SaveSceneAsResource( String resourceName )
        { 
            EngineOfEvermore.Scene.ObjectLibrary.SceneGraphContentResource
                .SaveContentAndReplace( resourceName, this.SceneGraph );
            
            if ( _lastSavedVersion != _commandStack.Version )
            {
                _lastSavedVersion = _commandStack.Version;

                if ( this.HasUnsavedChangesChanged != null )
                {
                    this.HasUnsavedChangesChanged( this );
                }
            }

            if ( _associatedResourceName != resourceName )
            {
                _associatedResourceName = resourceName;

                if ( this.NameOfAssociatedResourceChanged != null )
                {
                    this.NameOfAssociatedResourceChanged( this );
                }
            }
        }

        public String NameOfAssociatedResource
        {
            get { return _associatedResourceName; }
        }

        public bool HasUnsavedChanges
        {
            get { return _commandStack.Version != _lastSavedVersion; }
        }

        public SceneGraph SceneGraph
        {
            get { return _sceneGraph; }
        }

        public ISceneSelection Selection
        {
            get { return _sceneSelection; }
        }
 
        public CommandStack CommandStack
        {
            get { return _commandStack; }
        }

        public void Dispose()
        {
            this.Dispose( true );
            GC.SuppressFinalize( this );
        }

        protected virtual void Dispose( bool disposing )
        {
            if ( !_disposed )
            {
                if ( disposing )
                {
                    _commandStack.Dispose();
                    AgateLib.Core.KeepAliveEvent -= _updateSceneGraphUpdater;

                    // SceneGraph, and SceneGraphContext should probably be disposable too...
                }

                _disposed = true;
            }
        }
    }
}
